import services from '@/services/demo';
import {
    ActionType,
    FooterToolbar,
    PageContainer,
    ProDescriptions,
    ProDescriptionsItemProps,
    ProTable,
} from '@ant-design/pro-components';
import {Avatar, Button, Divider, Drawer, message, Popconfirm, Space} from 'antd';
import React, {useRef, useState} from 'react';
import {authForceLogout, getUserList} from "@/services/demo/UserController";
import OffLineForm from "./components/OffLineForm";
import {Link, useParams} from "@@/exports";
import {groupGetGroupMemberList, groupGetGroups, groupKickGroup} from "@/services/group/GroupController";
import {PlusOutlined} from "@ant-design/icons";
import {GroupJoinSource, GroupRoleLevel} from "@/utils/enums";
import {formatToDate} from "@/utils/dateUtil";
import {hide} from "@floating-ui/dom";

const {addUser, queryUserList, deleteUser, modifyUser, getUsers} = services.UserController;

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.UserInfo) => {
    const hide = message.loading('正在添加');
    try {
        await addUser({...fields});
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('正在配置');
    try {
        await modifyUser(
            {
                userId: fields.id || '',
            },
            {
                name: fields.name || '',
                nickName: fields.nickName || '',
                email: fields.email || '',
            },
        );
        hide();

        message.success('配置成功');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};

const GroupMember: React.FC<unknown> = () => {
    const {groupID} = useParams();
    const actionRef = useRef<ActionType>();
    const [row, setRow] = useState<API.UserInfo>();
    const [selectedRowsState, setSelectedRows] = useState<API.UserInfo[]>([]);
    const columns: ProDescriptionsItemProps[] = [
        {
            title: '序号',
            dataIndex: 'index',
            align: "center",
            render: (text, record, index) => <span>{index + 1}</span>,
        },
        {
            title: '群成员头像',
            dataIndex: 'faceURL',
            valueType: 'text',
            align: "center",
            render: (text, record, index) => {
                return <Avatar shape="square" src={text}/>
            },
        },
        {
            title: '群员ID',
            dataIndex: 'userID',
            valueType: 'text',
            align: "center",
        },
        {
            title: '群员角色',
            dataIndex: 'roleLevel',
            valueType: 'text',
            align: "center",
            render: (text, record, index) => {
                return Object.keys(GroupRoleLevel).find(name => GroupRoleLevel[name] === text) || '';
            },
        },
        {
            title: '群昵称',
            dataIndex: 'nickname',
            valueType: 'text',
            align: "center",

        },
        {
            title: '入群时间',
            dataIndex: 'joinTime',
            valueType: 'text',
            align: "center",
            search: false,
            render: (text, record, index) => {
                return formatToDate(text);
            },
        },
        {
            title: '入群方式',
            dataIndex: 'joinSource',
            valueType: 'text',
            align: "center",
            search: false,
            render: (text, record, index) => {
                return Object.keys(GroupJoinSource).find(name => GroupJoinSource[name] === text) || '';
            },
        },

        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            align: "center",
            render: (_, record) => (
                <>
                    <Space>
                        <Popconfirm
                            title="是否确认移除?"
                            okText="是"
                            cancelText="否"
                            onConfirm={()=>{handleRemove(record.groupID,[record.userID],"后台移除")}}
                        >
                            <a onClick={(e) => {e.preventDefault()}}>移除</a>
                        </Popconfirm>
                    </Space>

                    {/*  <a
                        onClick={() => {
                            handleCurUser(record);
                            handleOfflineModalVisible(true);
                        }}
                    >
                        强制下线
                    </a>
                    <Divider type="vertical"/>
                    <Link to={`/user_manage/relation_list/${record.userID}`}>关系链</Link>*/}
                </>
            ),
        },
    ];



    /**
     *  删除节点
     * @param groupID
     * @param kickedUserIDs
     * @param reason
     */
    const handleRemove = async (groupID:string,kickedUserIDs:string[],reason:string) => {
        try {
            await groupKickGroup(groupID,kickedUserIDs,reason);
            hide();
            actionRef.current?.reload();
            message.success('删除成功，即将刷新');
            return true;
        } catch (error) {
            hide();
            message.error('删除失败，请重试');
            return false;
        }
    };



    return (
        <PageContainer
            header={{
                title: '群成员列表',
            }}
        >
            <ProTable<API.UserInfo>
                headerTitle=""
                actionRef={actionRef}
                rowKey="userID"
                search={false}
                request={async (params, sorter, filter) => {
                    let pagination = {
                        pageNumber: params.current,
                        showNumber: params.pageSize,

                    };
                    const {errCode, errMsg, errDlt, data} = await groupGetGroupMemberList(groupID, pagination);
                    return {
                        data: data.members || [],
                        success: true,
                        total: data.total
                    };
                }}
                pagination={{
                    pageSize: 10,
                    onChange: (page) => console.log(page),
                }}
                columns={columns}
                rowSelection={{
                    onChange: (_, selectedRows) => setSelectedRows(selectedRows),
                }}
                toolBarRender={() => [
                    /*  <Button
                          key="button"
                          icon={<PlusOutlined />}
                          onClick={() => {
                              actionRef.current?.reload();
                          }}
                          type="primary"
                      >
                          新建
                      </Button>,*/
                ]}

            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a style={{fontWeight: 600}}>{selectedRowsState.length}</a>{' '}
                            项&nbsp;&nbsp;
                        </div>
                    }
                >
                    {/* <Button
                        onClick={async () => {
                            await handleRemove(selectedRowsState);
                            setSelectedRows([]);
                            actionRef.current?.reloadAndRest?.();
                        }}
                    >
                        批量删除
                    </Button>
                    <Button type="primary">批量审批</Button>*/}
                </FooterToolbar>
            )}


            <Drawer
                width={600}
                open={!!row}
                onClose={() => {
                    setRow(undefined);
                }}
                closable={false}
            >
                {row?.name && (
                    <ProDescriptions<API.UserInfo>
                        column={2}
                        title={row?.name}
                        request={async () => ({
                            data: row || {},
                        })}
                        params={{
                            id: row?.name,
                        }}
                        columns={columns}
                    />
                )}
            </Drawer>
        </PageContainer>
    );
};

export default GroupMember;
